package com.yty.newconsult.utils;


import java.io.*;
import java.nio.charset.Charset;

/**
 * 对象序列化持久化工具
 *
 * @author zxc
 *
 */
public class SerializableUtil
{
    private static final String ISO_8859_1 = "ISO-8859-1";

    // 将对象序列化
    static public byte[] toByteArray(Object obj)
    {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try
        {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray();
            oos.close();
            bos.close();
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
        return bytes;
    }

    /**
     * 对象序列化之后转换为字符串
     *
     * @param obj
     * @return ISO-8859-1编码的字符串(ISO-8859-1编码在反序列化时二进制一致.utf-8则会在转化为byte数组时在头部多出两个??而导致失败)
     * @throws IOException
     */
    static public void toFile(Object obj, File file)
            throws IOException
    {
        FileOutputStream fos = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(obj);
        oos.close();
    }

    /**
     * 对象序列化之后转换为字符串
     *
     * @param obj
     * @return ISO-8859-1编码的字符串(ISO-8859-1编码在反序列化时二进制一致.utf-8则会在转化为byte数组时在头部多出两个??而导致失败)
     */
    static public String toStr(Object obj)
    {
        byte[] byteArray = toByteArray(obj);
        if (byteArray == null)
        {
            return null;
        }
        return new String(byteArray, Charset.forName(ISO_8859_1));
    }

    /**
     * 将序列化后的字符串反序列化为对象
     *
     * @param str
     * @return
     */
    static public Object toObject(String str)
    {
        return toObject(str.getBytes(Charset.forName(ISO_8859_1)));
    }

    // 反序列化
    static public Object toObject(byte[] bytes)
    {
        Object obj = null;
        try
        {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bis);
            obj = ois.readObject();
            ois.close();
            bis.close();
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
        catch (ClassNotFoundException ex)
        {
            ex.printStackTrace();
        }
        return obj;
    }

    /**
     * 从文件反序列化为对象
     *
     * @param file
     * @return
     */
    static public Object toObject(File file)
    {
        Object obj = null;
        try
        {
            FileInputStream in = new FileInputStream(file);
            ObjectInputStream ois = new ObjectInputStream(in);
            obj = ois.readObject();
            ois.close();
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
        catch (ClassNotFoundException ex)
        {
            ex.printStackTrace();
        }
        return obj;
    }


}